
********************************
****Construct JIVE estimator****
********************************

use "$data/endline_clean_merged.dta", clear

drop if sample2==1 // keep only endline random sample (focus of all analysis)

rename paid_receipt_union paid // otherwise instrument names too long

*Collector dummies
global collectors = "Aime	Andre	AnneMarie	Antoinette	Antho	Dominique	Jean	John	Joseph	Timothe	Isidore	Touby	Ilunga	Francois	Paulin	Charles	Donatien	Tony	Nana	Constantin	Augustin	Daniel	Boniface	Crispin	Richard	Florent	Henriette	Josue	Mado	Alain	Hyppolite	Solange	Alphonse	Christophe	Theo	Kapinga	Jerome JeanJacques	Raphael	Patrick	Camile	Junior	Jonathan	Tshibalu " 

foreach collector of global collectors {
gen `collector'_union =  col1_union == "`collector'"|col2_union == "`collector'" |col3_union == "`collector'" |col4_union == "`collector'"|col5_union == "`collector'"
}

sort a7
local counter = 1
foreach outcome of varlist paid registered {

forvalues x= 1/5 {
	cap drop col`x'_avg_u_`outcome'
	gen double col`x'_avg_u_`outcome' = . 
}
 
levelsof a7 if program==1
foreach poly in `r(levels)'{
	di in red "`poly': `counter' of 22,258 runs"
foreach collector of global collectors{
	di in red "`collector'"

*Carto-tablet union assignments
sum `outcome' if a7!=`poly' & `collector'_union==1  & program==1
quietly: replace col1_avg_u_`outcome'=`r(mean)' if a7==`poly' & `collector'_union==1 & col1_avg_u_`outcome'==.
quietly: replace col2_avg_u_`outcome'=`r(mean)' if a7==`poly' & `collector'_union==1 & col2_avg_u_`outcome'==. & col1_avg_u_`outcome'!=`r(mean)'
quietly: replace col3_avg_u_`outcome'=`r(mean)' if a7==`poly' & `collector'_union==1 & col3_avg_u_`outcome'==. & col1_avg_u_`outcome'!=`r(mean)' & col2_avg_u_`outcome'!=`r(mean)'
quietly: replace col4_avg_u_`outcome'=`r(mean)' if a7==`poly' & `collector'_union==1 & col4_avg_u_`outcome'==. & col1_avg_u_`outcome'!=`r(mean)' & col2_avg_u_`outcome'!=`r(mean)' & col3_avg_u_`outcome'!=`r(mean)'
quietly: replace col5_avg_u_`outcome'=`r(mean)' if a7==`poly' & `collector'_union==1 & col5_avg_u_`outcome'==. & col1_avg_u_`outcome'!=`r(mean)' & col2_avg_u_`outcome'!=`r(mean)' & col3_avg_u_`outcome'!=`r(mean)' & col4_avg_u_`outcome'!=`r(mean)'

local counter = `counter'+1
}
}
}

collapse (median) *_avg_*, by(a7)

foreach var in paid registered {
	egen `var'_jive_u_avg = rowmean(col1_avg_u_`var' col2_avg_u_`var' col3_avg_u_`var' col4_avg_u_`var' col5_avg_u_`var'), 
}

keep a7 paid_jive_u_avg registered_jive_u_avg

sort a7
save "$data/jive_instruments.dta", replace

